<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/6/8
 * Time: 14:52
 * Created by Created by Panxsoft.
 */

namespace App\Models\Store;

use App\Models\Concerns\ScopeFilterable;
use App\Models\Customer\Customer;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

/**
 * Class PackCategory
 *
 * @property int $id
 * @property string $name
 * @property int $priority
 * @property string|null image - 分类图片
 *
 * @property-read Pack[]|Collection packs
 * @property-read Pack latestPack
 * @property-read Customer customer
 *
 * @mixin Builder
 */
class PackCategory extends Model
{
    use ScopeFilterable;
    use Bosable;

    protected $table = 'pack_categories';

    protected $guarded = [];

    protected $key_bos_key_prefix = 'pack_categories/';

    /**
     * @used-by $customer
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function customer()
    {
        return $this->belongsTo(Customer::class,'customer_id','id');
    }

    /**
     * @used-by $packs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function packs()
    {
        return $this->hasMany(Pack::class,'pack_category_id','id');
    }

    /**
     * @used-by $latestPack
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function latestPack()
    {
        return $this
            ->hasOne(Pack::class,'pack_category_id','id')
            ->latest();
    }

    /**
     * @deprecated - 不再上传 image
     * @used-by $image
     *
     * @param $image
     *
     * @throws \Exception
     */
    public function setImageAttribute($image)
    {
        if (is_file($image)) {
            $this->attributes['image'] = $this->uploadPostFile($image, $this->key_bos_key_prefix);
        }else{
            $this->attributes['image'] = $image;
        }
    }

    /**
     * 使用整妆分类下的第一个整妆缩略图
     *
     * @return string|null
     */
    public function getImageAttribute(): ?string
    {
        if ($this->relationLoaded('latestPack')) {
            return $this->latestPack->thumb ?? null;
        }

        if ($this->relationLoaded('packs')) {
            return $this->packs->first()->thumb ?? null;
        }

        if (!$this->attributes['image']) return null;

        return $this->getStaticUrl($this->attributes['image']);
    }

}